package com.junki.faceserver.controller;

import com.cnsugar.ai.face.FaceHelper;
import com.cnsugar.ai.face.bean.Result;
import com.junki.faceserver.vo.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author junki
 * @date 2021/5/27 15:27
 */
@RestController
@RequestMapping("face")
public class FaceController {

    @Value("${junki.clientImageSavePath}")
    private String clientImageSavePath;

    // 比较两个人脸
    @RequestMapping("twoFaceCompare")
    public JsonResult twoFaceCompare(@RequestParam("face1") MultipartFile face1, @RequestParam("face2") MultipartFile face2, HttpServletRequest request) throws IOException {
        BufferedImage bufferedImage1 = ImageIO.read(face1.getInputStream());
        BufferedImage bufferedImage2 = ImageIO.read(face2.getInputStream());

        byte[] face1Array = FaceHelper.cropFace(bufferedImage1)[0];
        byte[] face2Array = FaceHelper.cropFace(bufferedImage2)[0];
        float[] features1 = FaceHelper.extractCroppedFace(face1Array);
        float[] features2 = FaceHelper.extractCroppedFace(face2Array);
        float result = FaceHelper.calculateSimilarity(features1, features2);

        String dateTimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        asyncSaveClientUploadImage(bufferedImage1, clientImageSavePath + "/twoFaceCompare/" + dateTimeStr + "-1.jpeg");
        asyncSaveClientUploadImage(bufferedImage2, clientImageSavePath + "/twoFaceCompare/" + dateTimeStr + "-2.jpeg");


        return JsonResult.builder().code(200).msg("比较成功").data(result).build();
    }

    // 注册人脸
    @RequestMapping("registerFace")
    public JsonResult registerFace(@RequestParam("face") MultipartFile face, @RequestParam("name") String name, HttpServletRequest request) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(face.getInputStream());

        boolean result = FaceHelper.register(name, bufferedImage);

        String dateTimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        asyncSaveClientUploadImage(bufferedImage, clientImageSavePath + "/registerFace/" + dateTimeStr + "-" + name + ".jpeg");

        return JsonResult.builder().code(200).msg("注册").data(result).build();
    }

    // 查找人脸
    @RequestMapping("searchFace")
    public JsonResult searchFace(@RequestParam("face") MultipartFile face, HttpServletRequest request) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(face.getInputStream());

        Result result = FaceHelper.search(bufferedImage);

        String dateTimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        asyncSaveClientUploadImage(bufferedImage, clientImageSavePath + "/searchFace/" + dateTimeStr + ".jpeg");

        return JsonResult.builder().code(200).msg("查找成功").data(result).build();
    }

    // 上传base64查找人脸
    @RequestMapping("searchFaceBase64")
    public JsonResult searchFaceBase64(@RequestParam("face") String face, HttpServletRequest request) throws IOException {

        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(face.substring(face.indexOf(",") + 1));
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BufferedImage bufferedImage = ImageIO.read(bais);

        Result result = FaceHelper.search(bufferedImage);
        bais.close();

        String dateTimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        asyncSaveClientUploadImage(bufferedImage, clientImageSavePath + "/searchFaceBase64/" + dateTimeStr + ".jpeg");

        return JsonResult.builder().code(200).msg("查找成功").data(result).build();
    }

    // 异步保存用户上传的图片
    @Async
    public void asyncSaveClientUploadImage(BufferedImage bufferedImage, String filename) throws IOException {
        ImageIO.write(bufferedImage, "jpeg", new File(filename));
    }

}
